<?php 	
	include('template/header.php');
	include_once("classess/paypal_config.php");
	include_once("classess/paypal.class.php");
	include('classess/user_subscribe.php');
	$usr = new User_subscribe();

	$paypalmode = ($PayPalMode=='sandbox') ? '.sandbox' : '';
?>
	<!-- Page Content -->
	<section  class="homepage-slider" id="home-slider">
		<div class="flexslider">
			<ul class="slides">
				<li style="display:block !important;">
					<img src="template/themes/images/first_banner_final.jpg" alt="No Image" />					
				</li>
			</ul>
		</div>			
	</section>
	<section class="main-content">
		<div class="row">
			<div class="span9">	
				<?php
					if(isset($_GET["token"]) && isset($_GET["PayerID"]))
					{
						//we will be using these two variables to execute the "DoExpressCheckoutPayment"
						//Note: we haven't received any payment yet.
						
						$token = $_GET["token"];
						$payer_id = $_GET["PayerID"];
						
						//get session variables
						$paypal_product = $_SESSION["paypal_products"];
						$paypal_data = '';
						$ItemTotalPrice = 0;

						foreach($paypal_product['items'] as $key=>$p_item)
						{		
							$paypal_data .= '&L_PAYMENTREQUEST_0_QTY'.$key.'='. urlencode($p_item['itm_qty']);
							$paypal_data .= '&L_PAYMENTREQUEST_0_AMT'.$key.'='.urlencode($p_item['itm_price']);
							$paypal_data .= '&L_PAYMENTREQUEST_0_NAME'.$key.'='.urlencode($p_item['itm_name']);
							 $paypal_data .= '&L_PAYMENTREQUEST_0_NUMBER'.$key.'='.urlencode($p_item['itm_code']);
							
							// item price X quantity
							$subtotal = ($p_item['itm_price']*$p_item['itm_qty']);
							
							//total price
							$ItemTotalPrice = ($ItemTotalPrice + $subtotal);
						}

						$padata = 	'&TOKEN='.urlencode($token).
									'&PAYERID='.urlencode($payer_id).
									'&PAYMENTREQUEST_0_PAYMENTACTION='.urlencode("SALE").
									$paypal_data.
									'&PAYMENTREQUEST_0_ITEMAMT='.urlencode($ItemTotalPrice).
									'&PAYMENTREQUEST_0_TAXAMT='.urlencode($paypal_product['assets']['tax_total']).
									'&PAYMENTREQUEST_0_SHIPPINGAMT='.urlencode($paypal_product['assets']['shippin_cost']).
									'&PAYMENTREQUEST_0_HANDLINGAMT='.urlencode($paypal_product['assets']['handaling_cost']).
									'&PAYMENTREQUEST_0_SHIPDISCAMT='.urlencode($paypal_product['assets']['shippin_discount']).
									'&PAYMENTREQUEST_0_INSURANCEAMT='.urlencode($paypal_product['assets']['insurance_cost']).
									'&PAYMENTREQUEST_0_AMT='.urlencode($paypal_product['assets']['grand_total']).
									'&PAYMENTREQUEST_0_CURRENCYCODE='.urlencode($PayPalCurrencyCode);

						//We need to execute the "DoExpressCheckoutPayment" at this point to Receive payment from user.
						$paypal= new MyPayPal();
						$httpParsedResponseAr = $paypal->PPHttpPost('DoExpressCheckoutPayment', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
						
						//Check if everything went ok..
						if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) 
						{
							$transId = urldecode($httpParsedResponseAr["PAYMENTINFO_0_TRANSACTIONID"]);	
							
							if('Completed' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"])
							{
								echo '<div style="color:green">Payment Received! Your product will be sent to you very soon!</div>';
							}
							elseif('Pending' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"])
							{
								echo '<div style="color:red">Transaction Complete, but payment is still pending! '.
								'You need to manually authorize this payment in your <a target="_new" href="http://www.paypal.com">Paypal Account</a></div>';
							}

							// we can retrive transection details using either GetTransactionDetails or GetExpressCheckoutDetails
							// GetTransactionDetails requires a Transaction ID, and GetExpressCheckoutDetails requires Token returned by SetExpressCheckOut
							$padata = 	'&TOKEN='.urlencode($token);
							$paypal= new MyPayPal();
							$httpParsedResponseAr = $paypal->PPHttpPost('GetExpressCheckoutDetails', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);

							if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) 
							{							
								$buyerName = urldecode($httpParsedResponseAr["FIRSTNAME"]).' '.urldecode($httpParsedResponseAr["LASTNAME"]);
								$buyerEmail = urldecode($httpParsedResponseAr["EMAIL"]);
								$ItemName = urldecode($httpParsedResponseAr["L_NAME0"]);
								$ItemNumber = urldecode($httpParsedResponseAr["L_NUMBER0"]);
								$ItemTotalPrice = urldecode($httpParsedResponseAr["L_AMT0"]);
								$ItemQTY = urldecode($httpParsedResponseAr["L_QTY0"]);
								$datetime = date('Y-m-d H:i:s');
								
								$update_pd_status = "UPDATE tbl_user_details SET via_paid='paypal' WHERE id='".$_SESSION['last_user_detail_id']."'";
								$user_update_pd_status = mysql_query($update_pd_status) or die(mysql_error());

								$update = "UPDATE tbl_user SET is_paid='1' WHERE id='".$_SESSION['last_user_id']."'";
								$user_update = mysql_query($update) or die(mysql_error());

								$insert_cart = "INSERT INTO tbl_cart_payment (user_id,course_id,user_detail_id,payment,ipn) values('".$_SESSION['last_user_id']."','".$_SESSION['course_id']."','".$_SESSION['last_user_detail_id']."','".$httpParsedResponseAr["L_AMT0"]."','".$transId."')";
								$query_insert_cart = mysql_query($insert_cart) or die(mysql_error());
								
								$reffered_by = '';
								
								$select_subscribe = "SELECT * FROM tbl_user WHERE id='".$_SESSION['last_user_id']."'";		
								$query_subscribe = mysql_query($select_subscribe) or die(mysql_error());
								$count_row_subscribe = mysql_num_rows($query_subscribe);
								
								if($count_row_subscribe>0){
									while($row = mysql_fetch_array($query_subscribe)){
										$reffered_by = $row['reffered_by'];
									}
								}

								if($reffered_by!=''){
									$reffrel_id = explode('_',$reffered_by);
									$email_reffrel = '';
									$percent_comm = '';
									$table = '';
									$course_fee = '';

									$select_user_admin_mail = "SELECT * FROM tbl_affiliate WHERE id = '".$reffrel_id[1]."'"; 
									$query_user_admin_mail = mysql_query($select_user_admin_mail) or die(mysql_error());
									if(mysql_num_rows($query_user_admin_mail) > 0){
										while($row_admin_mail = mysql_fetch_array($query_user_admin_mail)){
											$email_reffrel = $row_admin_mail['email'];
										}
									}

									$select_commission = "SELECT * FROM tbl_commission WHERE user_admin_id = '".$reffered_by."' AND course_id='".$_SESSION['course_id']."'"; 
									$query_commission = mysql_query($select_commission) or die(mysql_error());

									if(mysql_num_rows($query_commission) > 0){
										while($row_commission = mysql_fetch_array($query_commission)){
											$percent_comm = $row_commission['commission_percentage'];
										}
										$course_fee = $httpParsedResponseAr["L_AMT0"];
									}else{
										$select_course = "SELECT * FROM tbl_courses WHERE id='".$_SESSION['course_id']."'";
										$query_course = mysql_query($select_course) or die(mysql_error());

										if(mysql_num_rows($query_course) > 0){
											while($row_course = mysql_fetch_array($query_course)){
												$percent_comm = $row_course['course_commission'];
											}
										}

										$course_fee = $httpParsedResponseAr["L_AMT0"];
									}

									if($percent_comm){
										$commision_fee = $course_fee*$percent_comm;
										$total_commision = $commision_fee/100;

										$insert_commission = "INSERT INTO tbl_commission (user_admin_id,course_id,trainee_id,trainee_detail_id,commission_percentage,commission,commission_paid_status) VALUES ('a_".$reffrel_id[1]."','".$_SESSION['course_id']."','".$_SESSION['last_user_id']."','".$_SESSION['last_user_detail_id']."','".$percent_comm."','".$total_commision."','0')";
										$query_commission = mysql_query($insert_commission) or die(mysql_error());								
									}
								}								
								$_SESSION['reffered_by'] = ' ';
								$_SESSION['last_user_detail_id'] = ' ';
								$_SESSION['last_user_id'] = ' ';
								unset($_SESSION['reffered_by']);
								unset($_SESSION['last_user_detail_id']);
								unset($_SESSION['last_user_id']);
								die("<script>location.href = 'index.php?home=1&prv_msg_set=1'</script>");
							} else  {
								echo '<div style="color:red"><b>GetTransactionDetails failed:</b>'.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]).'</div>';

							}
						
						}else{
							echo '<div style="color:red"><b>Error : </b>'.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]).'</div>';
						}
					}
				?>
			</div>
			<?php include('template/right_panel.php'); ?>
		</div>
	</section>
	<!-- /.content-section-a -->	
   
<?php include('template/footer.php'); ?>